/**
 * app 接口 request 实例
 * */
// import axios from 'axios'
// import { errorInterceptors } from './interceptors'
import ENV from "@/config/ENV.js";
import store from "@/store";
import debounce from "lodash-es/debounce";
import {
  NEED_LOGIN_STATUS_CODE,
  REMOTE_LOGIN_STATUS_CODE,
} from "./codeTypes.js";
import { requestStaticHeader } from "./config.js";
import Request from "./utils/extendRequest.js";
const app = new Request();
app.config.timeout = 50000;
app.config.baseURL = ENV.apiBaseURL;
// app.config.header.platform = 'weChat_applet'
app.setConfig((config) => {
  config.header = {
    ...config.header,
    ...requestStaticHeader,
  };
  return config;
});
// content-type 全小写
app.config.header["content-type"] = "application/json";
app.interceptors.request.use(
  (config) => {
    (config.header.Authorization = store.getters.isLogin
      ? `Bearer ${store.state.token}`
      : ""),
      (config.header.openid = store.getters.getOpenId
        ? `${store.state.openId}`
        : "");
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
const reLaunchLogin = debounce(
  function (mes) {
    console.log("全局拦截,重新登录");
    store.commit("LOGIN_OUT");
    setTimeout(() => {
      uni.hideToast();
      uni.showToast({
        icon: "none",
        title: mes,
        duration: 2100,
      });
    }, 100);

    uni.reLaunch({
      url: "/pages/wxlogin/wxlogin",
    });
  },
  1000,
  {
    leading: true,
    trailing: false,
  }
);
app.interceptors.response.use(
  (response) => {
    let serviceCode = response.data.code;
    if (serviceCode === NEED_LOGIN_STATUS_CODE) {
      reLaunchLogin("登录过期,请重新登录!");
      return Promise.reject(response);
    } else if (serviceCode === REMOTE_LOGIN_STATUS_CODE) {
      reLaunchLogin("请重新登录!");
      return Promise.reject(response);
    }
    return response;
  },
  (error) => {
    // errorInterceptors(error)
    return Promise.reject(error);
  }
);

export default app;
